﻿$(function () {
    var sourceType = $("#hSourceType").val();
    if (sourceType == "0") {
        //$.MiniUEditorInit("RequeatReason", 750, 105, true);  //迷你加载
        $.MiniUEditorInit($("#hid").val(), "ContractManagement/ContractExpenseList/RequeatReason", "RequeatReason", 1055, 105, true);  //迷你加载
    }
    else {
        //$.MiniUEditorInit("RequeatReason", 750, 105, false);  //迷你加载
        $.MiniUEditorInit($("#hid").val(), "ContractManagement/ContractExpenseList/RequeatReason", "RequeatReason", 1055, 105, false);  //迷你加载
    }

    //当页面首次刷新的时候执行的事件
    var expenseID = $("#hExpenseID").val();
    initTable(expenseID);

    //合同ID
    var contractID = $("#hContractID").val();
    var contractStages = $("#hContractStages").val();
    initOtherTable(contractID, contractStages);  //参数1：合同/标段ID，参数2：期次

    //测试
    //$.EasyuiSlide(contractID);

    var contractSource = $("#hContractSource").val();
    if (contractSource == "Construction") {
        //$('#trCommon').hide();
        var trCommom = document.getElementById('trCommon');
        var table = trCommom.parentNode;
        table.removeChild(trCommom);
    }
    else {
        //$('#trConstruction').hide();
        var trConstruction = document.getElementById('trConstruction');
        var table = trConstruction.parentNode;
        table.removeChild(trConstruction);
    }

    if (sourceType == '0') {
        $('#RequestPerson').attr("disabled", "disabled");
        $('#RequestDate').attr("disabled", "disabled");
        $('#Attachment').attr("disabled", "disabled");
        $('#PayNum').attr("disabled", "disabled");

        if (contractSource == "Construction") {
            $('#btnSelectConstructionContractEstimate').linkbutton('enable');
        }
    }
});

function initTable(expenseID) {
    $('#myDataGrid').datagrid({
        url: '/ProcessedTask/ProcessedTaskList?recordID=' + expenseID,
        fitColumns: true,
        nowrap: true,
        autoRowHeight: false,
        striped: true,
        collapsible: true,
        pagination: true,
        pageSize: 20,
        rownumbers: true,
        remoteSort: false,
        idField: 'ID',
        singleSelect: true,
        columns: [[
                    { title: '节点名称', field: 'CurrentProcessNodeName', width: 200, sortable: true },
                    { title: '审批意见', field: 'ApprovalOpinion', width: 300, sortable: true },
                    { title: '处理人部门', field: 'CurrentProcessPersonDepartmentName', width: 100, sortable: true },
                    { title: '处理人', field: 'CurrentProcessPersonName', width: 100, sortable: true },
                    { title: '处理时间', field: 'ProcessTimeFormat', width: 100, sortable: true }
        ]]
    });

    $('#myCirculatedDataGrid').datagrid({
        url: '/FlowProcessMessage/GetFlowProcessMessageListForReceipt?recordID=' + expenseID + "&processType=1",
        iconCls: 'icon-bricks',
        nowrap: true,
        autoRowHeight: false,
        striped: true,
        collapsible: true,
        pagination: true,
        pageSize: 20,
        remoteSort: false,
        idField: 'ID',
        singleSelect: true,
        columns: [[
                    { title: '描述', field: 'DisplayText', width: 600, sortable: true },
                    { title: '时间', field: 'AssociatedDate', width: 200, sortable: true },
        ]]
    });

    $('#myReceiptDataGrid').datagrid({
        url: '/FlowProcessMessage/GetFlowProcessMessageListForReceipt?recordID=' + expenseID + "&processType=2",
        iconCls: 'icon-bricks',
        nowrap: true,
        autoRowHeight: false,
        striped: true,
        collapsible: true,
        pagination: true,
        pageSize: 20,
        remoteSort: false,
        idField: 'ID',
        singleSelect: true,
        columns: [[
                    { title: '描述', field: 'DisplayText', width: 600, sortable: true },
                    { title: '时间', field: 'AssociatedDate', width: 200, sortable: true },
        ]]
    });
}

//对支表的处理
function initOtherTable(contractID, contractStages) {
    //支表一-上（列表）
    $('#tbFirstTopList').datagrid({
        url: '/Expense/GetVMExpenseFirstTopList?sectionID=' + contractID + '&periodID=' + contractStages,
        //fitColumns: true,
        nowrap: true,
        autoRowHeight: false,
        striped: true,
        collapsible: true,
        pagination: false,
        pageSize: 20,
        rownumbers: false,
        remoteSort: false,
        idField: 'ID',
        singleSelect: true,
        columns: [[
                    { title: '名称', field: 'Name', width: 210, sortable: false },
                    { title: '合计', field: 'Total', width: 100, sortable: false },
                    { title: '100章', field: 'OneOOZ', width: 100, sortable: false },
                    { title: '200章', field: 'TwoOOZ', width: 100, sortable: false },
                    { title: '300章', field: 'ThreeOOZ', width: 100, sortable: false },
                    { title: '400章', field: 'FourOOZ', width: 100, sortable: false },
                    { title: '500章', field: 'FiveOOZ', width: 100, sortable: false },
                    { title: '600章', field: 'SixOOZ', width: 100, sortable: false },
                    { title: '700章', field: 'SevenOOZ', width: 100, sortable: false },
                    { title: '暂列金', field: 'ProvisionalMoney', width: 100, sortable: false },
                    { title: '专项暂列金', field: 'ProProvisionalMoney', width: 100, sortable: false }
        ]]
    });

    //支表一-下（列表）
    $('#tbFirstBottomList').datagrid({
        url: '/Expense/GetVMExpenseFirstBottomList?sectionID=' + contractID + '&periodID=' + contractStages,
        //fitColumns: true,
        nowrap: true,
        autoRowHeight: false,
        striped: true,
        collapsible: true,
        pagination: false,
        pageSize: 20,
        rownumbers: false,
        remoteSort: false,
        idField: 'ID',
        singleSelect: true,
        columns: [[
                    { title: '分类名称', field: 'LeftName', width: 90, sortable: false },
                    { title: '名称', field: 'RightName', width: 120, sortable: false },
                    { title: '合计', field: 'Total', width: 100, sortable: false },
                    { title: '100章', field: 'OneOOZ', width: 100, sortable: false },
                    { title: '200章', field: 'TwoOOZ', width: 100, sortable: false },
                    { title: '300章', field: 'ThreeOOZ', width: 100, sortable: false },
                    { title: '400章', field: 'FourOOZ', width: 100, sortable: false },
                    { title: '500章', field: 'FiveOOZ', width: 100, sortable: false },
                    { title: '600章', field: 'SixOOZ', width: 100, sortable: false },
                    { title: '700章', field: 'SevenOOZ', width: 100, sortable: false },
                    { title: '暂列金', field: 'ProvisionalMoney', width: 100, sortable: false },
                    { title: '专项暂列金', field: 'ProProvisionalMoney', width: 100, sortable: false }
        ]],
        //合并单元格
        onLoadSuccess: function (data) {
            if (data.rows.length > 1) {
                //var tTable = $("#myDataGrid");
                //mergeCellsGroupByField(tTable, "UserName,RealName,Email,Contactphone,Description,AddDate", 0, data.rows.length);
                //以上合并方法是不是有问题呢？先只合并用户名
                mergeCellsByField("tbFirstBottomList", "LeftName");
            }
        }
    });

    //支表一-扣款（列表）
    $('#tbFirstCutPaymentList').datagrid({
        url: '/Expense/GetVMExpenseFirstCutPaymentList?sectionID=' + contractID + '&periodID=' + contractStages,
        //fitColumns: true,
        nowrap: true,
        autoRowHeight: false,
        striped: true,
        collapsible: true,
        pagination: false,
        pageSize: 20,
        rownumbers: false,
        remoteSort: false,
        idField: 'ID',
        singleSelect: true,
        columns: [[
                    { title: '分类名称', field: 'LeftName', width: 90, sortable: false },
                    { title: '名称', field: 'RightName', width: 120, sortable: false },
                    { title: '扣回动员预付款', field: 'CutPaymentForPerson', width: 100, sortable: false },
                    { title: '扣回甲供材料款', field: 'CutPaymentForMaterial', width: 100, sortable: false },
                    { title: '扣税金(3.33%）', field: 'CutPaymentForTaxation', width: 100, sortable: false },
                    { title: '扣保留金', field: 'CutPaymentForSave', width: 100, sortable: false },
                    { title: '扣民工工资保证金', field: 'CutPaymentForSalary', width: 100, sortable: false },
                    { title: '扣违约金', field: 'CutPaymentForPenalty', width: 100, sortable: false },
                    { title: '扣款合计', field: 'CutPaymentForTotal', width: 100, sortable: false },
                    { title: '实际支付金额', field: 'CutPaymentForReality', width: 100, sortable: false },
        ]],
        //合并单元格
        onLoadSuccess: function (data) {
            if (data.rows.length > 1) {
                //var tTable = $("#myDataGrid");
                //mergeCellsGroupByField(tTable, "UserName,RealName,Email,Contactphone,Description,AddDate", 0, data.rows.length);
                //以上合并方法是不是有问题呢？先只合并用户名
                mergeCellsByField("tbFirstCutPaymentList", "LeftName");
            }
        }
    });

    //支表二
    $('#tbSecondList').datagrid({
        url: '/Expense/GetVMExpenseSecondList?sectionID=' + contractID + '&periodID=' + contractStages,
        fitColumns: true,
        nowrap: true,
        autoRowHeight: false,
        striped: true,
        collapsible: true,
        pagination: false,
        pageSize: 20,
        rownumbers: false,
        remoteSort: false,
        singleSelect: true,
        sortName: 'OrderNo',
        columns: [[
                    { title: 'OrderNo', field: 'OrderNo', hidden: true },
                    { title: '名称', field: 'Name', width: 250, sortable: false },
                    { title: '100章', field: 'OneOOZ', width: 100, sortable: false },
                    { title: '200章', field: 'TwoOOZ', width: 100, sortable: false },
                    { title: '300章', field: 'ThreeOOZ', width: 100, sortable: false },
                    { title: '400章', field: 'FourOOZ', width: 100, sortable: false },
                    { title: '500章', field: 'FiveOOZ', width: 100, sortable: false },
                    { title: '600章', field: 'SixOOZ', width: 100, sortable: false },
                    { title: '700章', field: 'SevenOOZ', width: 100, sortable: false },
                    { title: '暂列金', field: 'ProvisionalMoney', width: 125, sortable: false },
                    { title: '专项暂列金', field: 'ProProvisionalMoney', width: 125, sortable: false }
        ]]
    });

    //支表三（列表）
    $('#tbThirdList').datagrid({
        url: '/Expense/GetVMExpenseThirdList?sectionID=' + contractID + '&periodID=' + contractStages,
        //fitColumns: true,
        nowrap: true,
        autoRowHeight: false,
        striped: true,
        collapsible: true,
        pagination: false,
        pageSize: 20,
        rownumbers: true,
        remoteSort: false,
        idField: 'ID',
        singleSelect: true,
        columns: [[
                    { title: '清单编号', field: 'ListNo', width: 80, sortable: true, rowspan: 2 },
                    { title: '细目名称', field: 'ListName', width: 120, sortable: true, rowspan: 2 },
                    { title: '单位', field: 'Unit', width: 50, sortable: true, rowspan: 2 },
                    { title: '单价', field: 'Price', width: 60, sortable: true, rowspan: 2 },
                    { title: '合同数量', field: 'ContractCount', width: 60, sortable: true, rowspan: 2 },
                    { title: '合同金额(元)', field: 'ContractMoney', width: 80, sortable: true, rowspan: 2 },
                    { title: '施工图纸数量', field: 'BuildPaperCount', width: 80, sortable: true, rowspan: 2 },
                    { title: '施工图纸金额(元)', field: 'BuildPaperMoney', width: 90, sortable: true, rowspan: 2 },
                    { title: '变更后数量', field: 'ChangeCount', width: 70, sortable: true, rowspan: 2 },
                    { title: '变更后金额(元)', field: 'ChangeMoney', width: 90, sortable: true, rowspan: 2 },

                    { title: '本期末累计完成', field: '', width: 90, sortable: true, colspan: 2 },
                    { title: '上期末累计完成', field: '', width: 90, sortable: true, colspan: 2 },
                    { title: '本期完成', field: '', width: 90, sortable: true, colspan: 2 },
        ],
                    [
                         { title: '数量', field: 'ThisPeriodTotalFinishCount', align: 'center', width: 70 },
                         { title: '金额(元)', field: 'ThisPeriodTotalFinishMoney', align: 'center', width: 80 },
                         { title: '数量', field: 'PreviousPeriodTotalFinishCount', align: 'center', width: 70 },
                         { title: '金额(元)', field: 'PreviousPeriodTotalFinishMoney', align: 'center', width: 80 },
                         { title: '数量', field: 'ThisPeriodFinishCount', align: 'center', width: 70 },
                         { title: '金额(元)', field: 'ThisPeriodFinishMoney', align: 'center', width: 70 }
                    ]]
    });
}

function SelectConstructionContractEstimate() {
    var sourceType = $("#hSourceType").val();
    if (sourceType != 1) {
        $.EasyuiSlide("编辑状态下不允许更改期次及金额");
        return;
    }

    var contractID = $("#hContractID").val();
    var handleState = $("#hHandleState").val();
    var processType = $("#hProcessType").val();
    var associatedNodeCode = $("#hAssociatedNodeCode").val();
    var lastUpdateUserDepartment = $("#hLastUpdateUserDepartment").val();
    var lastUpdateUser = $("#hLastUpdateUser").val();
    var expenseID = $("#hExpenseID").val();
    showMyWindow("#expenseWindow", "施工合同计量期选择", "/Expense/ConstructionContractEstimateList?contractID=" + contractID + "&handleState=" + handleState + "&sourceType=" + sourceType + "&processType=" + processType + "&associatedNodeCode=" + associatedNodeCode + "&lastUpdateUserDepartment=" + lastUpdateUserDepartment + "&lastUpdateUser=" + lastUpdateUser + "&expenseID=" + expenseID, 600, 450, true, false);
}

function UpdateConstructionContractEstimate() {
    if ($("#hContractStages").val() == 0) {
        $.EasyuiSlide("还没有选择期次信息，不能更新！");
    }
    else {
        var contractID = $("#hContractID").val();
        var contractStages = $("#hContractStages").val()
        $.post("/Expense/UpdateConstructionContractEstimate?contractID=" + contractID + "&contractStages=" + contractStages, function (res) {
            if (res.Message == "更新成功！") {
                $("#hApprovalMoney").val(res.ApproveMoney);
                $("#ContractStagesStr").val("第" + contractStages + "期:" + res.ApproveMoney);
            }
            $.EasyuiSlide(res.Message);
        });
    }
}

function GetExpenseBillListJson() {
    return $("#hExpenseBillListJson").val();
}

function SetApprovalMoneyAndGetExpenseBillListJson(sumMoney, jsonValue, contractStages) {
    $("#hApprovalMoney").val(sumMoney);
    $("#ContractStagesStr").val("第" + contractStages + "期:" + sumMoney);
    $("#hExpenseBillListJson").val(jsonValue);
    $("#hContractStages").val(contractStages);

    //合同ID
    var contractID = $("#hContractID").val();
    initOtherTable(contractID, contractStages);  //参数1：合同/标段ID，参数2：期次
    //$.EasyuiSlide(contractStages);  //测试
}

var Expense =
    {
        Save: function () {
            var approvalMoney = $("#hApprovalMoney").val();
            if (approvalMoney == 0) {
                $.EasyuiSlide("请填写本次申请金额！");
                return false;
            }

            var payNum = $("#PayNum").val();
            if (payNum == '') {
                $.EasyuiSlide("请填写支付编号！");
                return false;
            }

            $('#frmExpense').form('submit', {
                url: '/Expense/Save',
                onSubmit: function () {

                },
                success: function (data) {
                    if (data == '保存成功!') {
                        $('#btnCirculation').linkbutton('enable');
                        $('#btnCirculated').linkbutton('enable');
                    }
                    $.EasyuiSlide(data);
                },
                fail: function (data) {
                    $.EasyuiSlide(data);
                }
            });
        },

        Circulation: function () {
            var flowCode = $("#hFlowCode").val();
            var id = $("#hExpenseID").val();
            var handleState = $("#hHandleState").val();
            var nodeCode = $("#hAssociatedNodeCode").val();
            var processUserDepartment = $("#hLastUpdateUserDepartment").val();
            var processUser = $("#hLastUpdateUser").val();

            $('#frmExpense').form('submit', {
                url: '/Expense/Save?vilidateCirculation=1',
                onSubmit: function () {

                },
                success: function (data) {
                    if (data == '保存成功!') {
                        showMyWindow("#expenseWindow", "流程审批", "/Flow/CirculationFlow?flowCode=" + flowCode + "&recordID=" + id + "&handleState=" + handleState + "&currentFlowNodeCode=" + nodeCode + "&processUserDepartment=" + processUserDepartment + "&processUser=" + processUser, 500, 250, true, false);
                    }
                    else {
                        $.EasyuiSlide(data);
                    }
                },
                fail: function (data) {
                    $.EasyuiSlide(data);
                }
            });
        },

        Withdraw: function () {
            var withdrawNodeCode = $("#hProcessdOrCirculatedNodeCode").val();
            $('#frmExpense').form('submit', {
                url: '/Expense/Withdraw?withdrawNodeCode=' + withdrawNodeCode,
                onSubmit: function () {
                },
                success: function (data) {
                    window.parent.CloseWindow('撤回成功！');
                },
                fail: function (data) {
                    $.EasyuiSlide(data);
                }
            });
        },

        Back: function () {
            var flowCode = $("#hFlowCode").val();
            var id = $("#hExpenseID").val();
            var nodeCode = $("#hAssociatedNodeCode").val();
            showMyWindow("#expenseWindow", "流程回退", "/Flow/BackFlow?flowCode=" + flowCode + "&recordID=" + id + "&flowNodeCode=" + nodeCode, 550, 400, true, false);
        },

        Cancel: function () {
            var flowCode = $("#hFlowCode").val();
            var id = $("#hExpenseID").val();
            $.post("/Expense/Cancel?flowCode=" + flowCode + "&id=" + id, function (res) {
                if (res == "Success") {
                    window.parent.CloseWindow('终止成功！');
                }
                else {
                    $.EasyuiSlide(res);
                }
            });
        },

        Circulated: function () {
            var flowCode = $("#hFlowCode").val();
            var id = $("#hExpenseID").val();
            var nodeCode = $("#hProcessdOrCirculatedNodeCode").val();
            var department = $("#hProcessdOrCirculatedUserDepartment").val();
            showMyWindow("#expenseWindow", "流程传阅", "/Flow/CirculatedFlow?flowCode=" + flowCode + "&recordID=" + id + "&nodeCode=" + nodeCode + "&department=" + department, 400, 400, true, false);
        },

        Receipt: function () {
            var flowCode = $("#hFlowCode").val();
            var messageID = $("#hSourceID").val();
            showMyWindow("#expenseWindow", "流程已阅", "/Flow/ReceiptFlow?flowCode=" + flowCode + "&messageID=" + messageID, 500, 250, true, false);
        },

        Reminders: function () {
            var flowCode = $("#hFlowCode").val();
            var id = $("#hExpenseID").val();
            $.post("/Expense/Reminders?flowCode=" + flowCode + "&id=" + id, function (res) {
                if (res == "Success") {
                    window.parent.CloseWindow('催办成功！');
                }
                else {
                    $.EasyuiSlide(res);
                }
            });
        }
    }

function CloseSelf() {
    var handleState = $("#hHandleState").val();
    window.parent.cancelPopWindow(handleState);
}

function PreviewProcessGraph(title, index) {
    if (index == 1) {
        var flowCode = $("#hFlowCode").val();
        var expenseID = $("#hExpenseID").val();
        $.post("/Expense/GenerateGraph?flowCode=" + flowCode + "&id=" + expenseID, function (res) {
            var container = document.getElementById('graphContainer');
            if (container.hasChildNodes()) {
                $("#graphContainer").empty()
            }
            PreviewGraph(container, res);
        }
        )
    }
}

function PreviewCharts(title, index) {
    if (index == 1) {
        var projectID = $("#hProjectID").val();
        var contractID = $("#hContractID").val();
        var contractStages = $("#hContractStages").val();
        if (contractStages > 0) {
            $.post("/Expense/GenerateChart?projectID=" + projectID + "&contractID=" + contractID + "&periodID=" + contractStages, function (res) {
                var myChart = new JSChart('chartsContainer', 'line');

                var myData = new Array();
                for (var i = 0; i < res.lstPointView.length; i++) {
                    var x = res.lstPointView[i].X;
                    var y = res.lstPointView[i].Y;
                    var subData = [x, y];
                    myData[i] = subData;
                }

                var myDataOne = new Array();
                for (var i = 0; i < res.lstPointViewOne.length; i++) {
                    var x = res.lstPointViewOne[i].X;
                    var y = res.lstPointViewOne[i].Y;
                    var subDataOne = [x, y];
                    myDataOne[i] = subDataOne;
                }

                var myDataTwo = new Array();
                for (var i = 0; i < res.lstPointViewTwo.length; i++) {
                    var x = res.lstPointViewTwo[i].X;
                    var y = res.lstPointViewTwo[i].Y;
                    var subDataTwo = [x, y];
                    myDataTwo[i] = subDataTwo;
                }

                if (myData.length > 0) {
                    myChart.setDataArray(myData, '计划完成');
                    //for (var i = 0; i < res.lstPointView.length; i++) {
                    //    var x = res.lstPointView[i].X;
                    //    var y = res.lstPointView[i].Y;
                    //    myChart.setTooltip([x, y, '计划完成']);
                    //}
                }
                //if (myDataOne.length > 0) {
                //    myChart.setDataArray(myDataOne, '实际完成');
                //    myChart.setLineColor('#00FF00', '实际完成');
                //    //for (var i = 0; i < res.lstPointViewOne.length; i++) {
                //    //    var x = res.lstPointViewOne[i].X;
                //    //    var y = res.lstPointViewOne[i].Y;
                //    //    myChart.setTooltip([x, y, '实际完成']);
                //    //}
                //}
                if (myDataTwo.length > 0) {
                    myChart.setDataArray(myDataTwo, '实际支付');
                    myChart.setLineColor('#C83636', '实际支付');
                    //for (var i = 0; i < res.lstPointViewTwo.length; i++) {
                    //    var x = res.lstPointViewTwo[i].X;
                    //    var y = res.lstPointViewTwo[i].Y;
                    //    myChart.setTooltip([x, y, '实际支付']);
                    //}
                }

                myChart.resize(1500, 400);
                myChart.setAxisPaddingTop(35);
                myChart.setAxisPaddingBottom(35);
                myChart.setTitle('                                      2014年                                                                            2015年                                                                            2016年')
                myChart.setTitleColor('#37379E');
                myChart.setTitleFontSize(15);
                myChart.setTitlePosition('left');

                myChart.setAxisValuesNumberX(37);
                myChart.setIntervalStartX(0);
                myChart.setIntervalEndX(36);
                myChart.setAxisValuesNumberY(11);
                myChart.setIntervalStartY(0);
                myChart.setIntervalEndY(100);

                myChart.setLegendShow(true);

                myChart.setAxisNameX("月数");
                myChart.setAxisNameY("%");
                myChart.draw();
            }
            )
        }
    }
}

//关闭弹出窗口，按条件刷新主界面
//0：取消，1：发送，2：回退，3：传阅，4：已阅
function CloseWindow(closeType, data) {
    colseMyWindow("#expenseWindow");
    if (closeType != 0) {
        window.parent.CloseWindow(data);
    }
}
